package com.lbj.service.impl;

import com.lbj.dao.TopicDao;
import com.lbj.dao.impl.TopicDaoImpl;
import com.lbj.domain.Topic;
import com.lbj.service.TopicService;

import java.util.List;
import java.util.Map;

public class TopicServiceImpl implements TopicService {
    private final TopicDao topicDao = new TopicDaoImpl();

    @Override
    public List<Topic> getTopics() {
        return topicDao.getTopics();
    }

    @Override
    public Boolean deleteTopicById(String id) {
        int row = topicDao.deleteTopicById(id);
        return row == 1;
    }

    @Override
    public Boolean addTopic(Topic topic) {
        int row = topicDao.addTopic(topic);
        return row == 1;
    }

    @Override
    public List<Topic> getTopicsByCondition(Map<String, String> conditions) {
        return topicDao.getTopicsByCondition(conditions);
    }

    @Override
    public Topic getTopicById(String id) {
        return topicDao.getTopicById(id);
    }

    @Override
    public boolean updateInfo(Topic topic) {
        return topicDao.updateTopicInfo(topic) == 1;
    }

    @Override
    public int getUserThumbCount(List<Topic> topics) {
        int thumbCount = 0;
        for (Topic topic : topics) {
            thumbCount += topic.getThumbsCount();
        }
        return thumbCount;
    }

    @Override
    public int geUserCollectionCount(List<Topic> topics) {
        int collectionCount = 0;
        for (Topic topic : topics) {
            collectionCount += topic.getCollectionCount();
        }
        return collectionCount;
    }

    @Override
    public int getUserTopicCount(List<Topic> topics) {
        return topics.size();
    }

    @Override
    public List<Topic> getTopicsTop() {
        return topicDao.getTopicsTop();
    }

    @Override
    public List<Topic> pageList(int pageNum, int pageSize) {
        int start = (pageNum - 1) * pageSize;
        return topicDao.pageList(start, pageSize);
    }

    @Override
    public int getTotalPage(int totalCount, int pageSize) {
        return totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1;
    }

    @Override
    public int getTotalCount() {
        return topicDao.getTotalCount();
    }

    @Override
    public Boolean top(String id) {
        Topic topic = topicDao.getTopicById(id);
        StringBuilder status = new StringBuilder(topic.getStatus());
        status.setCharAt(0,'1');
        topic.setStatus(new String(status));
        return updateInfo(topic);
    }

    @Override
    public Boolean essence(String id) {
        Topic topic = topicDao.getTopicById(id);
        StringBuilder status = new StringBuilder(topic.getStatus());
        status.setCharAt(1,'1');
        topic.setStatus(new String(status));
        return updateInfo(topic);
    }
}
